package io.itit.ecp.admin.server.service.impl;

import icu.mhb.mybatisplus.plugln.base.service.impl.JoinServiceImpl;
import io.itit.ecp.admin.common.enums.IDataRangeEnums;
import io.itit.ecp.admin.server.entity.DataRangeEntity;
import io.itit.ecp.admin.server.entity.DataRangeSceneEntity;
import io.itit.ecp.admin.server.mapper.DataRangeMapper;
import io.itit.ecp.admin.server.service.IDataRangeSceneService;
import io.itit.ecp.admin.server.service.IDataRangeService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *
 * @Author：Roy
 * @Description：数据范围服务实现类
 * @Date：Create by 2024-01-17 16:55:06
 */
@Service
public class DataRangeServiceImpl extends JoinServiceImpl<DataRangeMapper, DataRangeEntity> implements IDataRangeService {

    @Resource
    private IDataRangeSceneService dataRangeSceneService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean save(DataRangeEntity dataRange, List<String> sceneIdList) {
        return saveDataRangeScene(save(dataRange), dataRange, sceneIdList);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean update(DataRangeEntity dataRange, List<String> sceneIdList) {
        boolean updateFlag = lambdaUpdate().set(DataRangeEntity::getRangeName, dataRange.getRangeName())
                .set(DataRangeEntity::getRemark, dataRange.getRemark())
                .set(DataRangeEntity::getRangeLevel, dataRange.getRangeLevel())
                .eq(DataRangeEntity::getId, dataRange.getId())
                .update();
        // 明细表先增加后删
        dataRangeSceneService.lambdaUpdate().eq(DataRangeSceneEntity::getDataRangeId, dataRange.getId()).remove();
        return saveDataRangeScene(updateFlag, dataRange, sceneIdList);
    }

    private Boolean saveDataRangeScene(Boolean flag, DataRangeEntity dataRange, List<String> sceneIdList) {
        if (IDataRangeEnums.RangeLevel.rangeLevelAll.rangeLevel.equals(dataRange.getRangeLevel())) {
            return flag;
        }
        List<DataRangeSceneEntity> rangeSceneList = sceneIdList.stream().map(t -> build(t, dataRange.getId())).collect(Collectors.toList());
        return flag && dataRangeSceneService.saveBatch(rangeSceneList);
    }

    private DataRangeSceneEntity build(String sceneId, String dataRangeId) {
        DataRangeSceneEntity entity = new DataRangeSceneEntity();
        entity.setSceneId(sceneId);
        entity.setDataRangeId(dataRangeId);
        return entity;
    }

}